package com.szl.group.utils;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class JoinPointUtils {


    /**
     * 获取方法
     *
     * @param pjp
     * @return
     */
    public static Method getMethod(ProceedingJoinPoint pjp) {

        MethodSignature signature = (MethodSignature) pjp.getSignature();
        return signature.getMethod();

    }

    /**
     * 获取方法上的指定注解
     *
     * @param pjp
     * @param annotationClass
     * @param <T>
     * @return
     */
    public static <T extends Annotation> T getAnnotation(ProceedingJoinPoint pjp, Class<T> annotationClass) {
        return getMethod(pjp).getAnnotation(annotationClass);
    }

    /**
     * 获取目标方法
     *
     * @param point
     * @return
     */
    public static Method getTargetMethod(JoinPoint point) {
        try {

            Signature sig = point.getSignature();
            MethodSignature msi = (MethodSignature) sig;
            Object target = point.getTarget();

            return target.getClass().getMethod(msi.getName(), msi.getParameterTypes());

        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 获取目标方法上的指定注解
     *
     * @param pjp
     * @param annotationClass
     * @param <T>
     * @return
     */
    public static <T extends Annotation> T getTargetAnnotation(JoinPoint pjp, Class<T> annotationClass) {
        return getTargetMethod(pjp).getAnnotation(annotationClass);
    }
}
